package com.example.project3.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.example.project3.DetailActivity;
import com.example.project3.R;
import com.example.project3.adapter.ListItemAdapter;
import com.example.project3.model.ListItem;
import com.example.project3.viewmodel.HomeViewModel;

public class HomeFragment extends Fragment {
    private TextView tvRecommend;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private ListItemAdapter adapter;
    private HomeViewModel viewModel;
    private String currentInterest;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        
        // 初始化视图
        initViews(view);
        
        // 初始化ViewModel
        initViewModel();
        
        // 初始化RecyclerView
        initRecyclerView();
        
        // 观察LiveData
        observeData();
        
        // 恢复保存的状态
        if (savedInstanceState != null) {
            currentInterest = savedInstanceState.getString("interest");
        } else {
            // 从 SharedPreferences 获取兴趣
            SharedPreferences sp = requireActivity().getSharedPreferences("user_info", 0);
            currentInterest = sp.getString("interest", getString(R.string.no_interest));
        }
        
        updateRecommendText();
        
        return view;
    }

    /**
     * 初始化视图
     */
    private void initViews(View view) {
        tvRecommend = view.findViewById(R.id.tv_recommend);
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        recyclerView = view.findViewById(R.id.recycler_view);
    }

    /**
     * 初始化ViewModel
     */
    private void initViewModel() {
        viewModel = new ViewModelProvider(this).get(HomeViewModel.class);
    }

    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        // 设置布局管理器
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        
        // 创建适配器
        adapter = new ListItemAdapter();
        
        // 设置点击事件
        adapter.setOnItemClickListener(this::onItemClick);
        
        // 设置适配器
        recyclerView.setAdapter(adapter);
        
        // 设置下拉刷新监听
        swipeRefreshLayout.setOnRefreshListener(() -> viewModel.refreshData());
    }

    /**
     * 观察LiveData数据
     */
    private void observeData() {
        // 观察列表数据
        viewModel.getListData().observe(getViewLifecycleOwner(), listItems -> {
            if (listItems != null) {
                adapter.updateData(listItems);
            }
        });
        
        // 观察刷新状态
        viewModel.getIsRefreshing().observe(getViewLifecycleOwner(), isRefreshing -> {
            if (isRefreshing != null) {
                swipeRefreshLayout.setRefreshing(isRefreshing);
            }
        });
        
        // 观察错误信息
        viewModel.getErrorMessage().observe(getViewLifecycleOwner(), errorMessage -> {
            if (errorMessage != null && !errorMessage.isEmpty()) {
                Toast.makeText(getContext(), errorMessage, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 列表项点击事件
     */
    private void onItemClick(ListItem item) {
        Intent intent = new Intent(getContext(), DetailActivity.class);
        intent.putExtra("item", item);
        startActivity(intent);
    }

    /**
     * 更新推荐文本
     */
    private void updateRecommendText() {
        String recommendText = getString(R.string.recommend_content, currentInterest);
        tvRecommend.setText(recommendText);
    }

    /**
     * 提供外部更新兴趣的方法
     */
    public void setInterest(String interest) {
        currentInterest = interest;
        updateRecommendText();
    }

    /**
     * 保存Fragment状态
     */
    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("interest", currentInterest);
    }
}